package grape.wx.service.mp.reply.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import grape.base.rest.client.dict.DictClient;
import grape.base.service.dict.po.Dict;
import grape.common.service.common.dictenums.PublicDictEnums;
import grape.wx.service.mp.MpProperties;
import grape.wx.service.mp.reply.po.MpMsgReply;
import grape.wx.service.mp.reply.mapper.MpMsgReplyMapper;
import grape.wx.service.mp.reply.api.IMpMsgReplyService;
import grape.common.service.common.BaseServiceImpl;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.util.WxMpConfigStorageHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static grape.wx.service.mp.reply.po.MpMsgReply.event_type_dict_item_prefix;
import static grape.wx.service.mp.reply.po.MpMsgReply.xml_msg_type_dict_item_prefix;

/**
 * <p>
 * 公众号消息回复表 服务实现类
 * </p>
 *
 * @author yangwei
 * @since 2020-07-23
 */

@Service
public class MpMsgReplyServiceImpl extends BaseServiceImpl<MpMsgReplyMapper, MpMsgReply> implements IMpMsgReplyService {

    @Autowired
    private MpProperties mpProperties;
    @Autowired
    private DictClient dictClient;

    @Override
    public MpMsgReply getMatched(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
        String appId = WxMpConfigStorageHolder.get();
        assertParamNotEmpty(appId,"appId未获取到，这可能是一个bug");
        MpProperties.MpConfig mpConfig = mpProperties.abtainConfigByAppCodeOrAppId(appId);
        assertNotNull(mpConfig,"未获取到公众号配置，请检查配置");
        assertParamNotEmpty(mpConfig.getAppCode(),"appCode必须配置，appCode用来唯一标识一个公众号配置");
        MpMsgReply mpMsgReplyQuery = new MpMsgReply();
        mpMsgReplyQuery.setAppCode(mpConfig.getAppCode());
        QueryWrapper<MpMsgReply> queryWrapper = Wrappers.query(mpMsgReplyQuery).and(mpMsgReplyQueryWrapper -> {
            mpMsgReplyQueryWrapper.lambda().isNull(MpMsgReply::getMatchFromUser);
            return mpMsgReplyQueryWrapper;
        });
        // 接收人
        if(isStrEmpty(wxMessage.getFromUser())){
            queryWrapper.lambda().isNull(MpMsgReply::getMatchFromUser);
        }else {
            queryWrapper.and(qw-> {
                qw.lambda().isNull(MpMsgReply::getMatchFromUser).or().eq(MpMsgReply::getMatchFromUser, wxMessage.getFromUser());
                return qw;
            });
        }
        // xml消息类型
        if(isStrEmpty(wxMessage.getMsgType())){
            queryWrapper.lambda().isNull(MpMsgReply::getMatchMsgTypeDictId);
        }else {
            String msgType = xml_msg_type_dict_item_prefix + wxMessage.getMsgType();
            Dict dictByCode = dictClient.getDictByCode(msgType.toLowerCase());
            // 没有字典，直接返回空
            if (dictByCode == null) {
                return null;
            }
            queryWrapper.and(qw-> {
                qw.lambda().isNull(MpMsgReply::getMatchMsgTypeDictId).or().eq(MpMsgReply::getMatchMsgTypeDictId, dictByCode.getId());
                return qw;
            });
        }
        // 事件类型
        if(isStrEmpty(wxMessage.getEvent())){
            queryWrapper.lambda().isNull(MpMsgReply::getMatchEventTypeDictId);
        }else {
            String msgType = event_type_dict_item_prefix + wxMessage.getEvent();
            Dict dictByCode = dictClient.getDictByCode(msgType.toLowerCase());
            // 没有字典，直接返回空
            if (dictByCode == null) {
                return null;
            }
            queryWrapper.lambda().eq(MpMsgReply::getMatchEventTypeDictId, dictByCode.getId());
        }
        // 按权重优先级和更新时间倒序排序
        queryWrapper.lambda().orderByDesc(MpMsgReply::getPriority).orderByDesc(MpMsgReply::getUpdateAt);
        
        List<MpMsgReply> list = list(queryWrapper);

        for (MpMsgReply mpMsgReply : list) {
            if(test(wxMessage,mpMsgReply)){
                return mpMsgReply;
            }
        }
        return null;
    }

    /**
     * 判断是否匹配
     * @param wxMessage
     * @param mpMsgReply
     * @return
     */
    protected boolean test(WxMpXmlMessage wxMessage,MpMsgReply mpMsgReply) {
        return
                (mpMsgReply.getMatchFromUser() == null || mpMsgReply.getMatchFromUser().equals(wxMessage.getFromUser()))
                        &&
                        (mpMsgReply.getMatchMsgTypeDictId() == null || dictClient.getDictById(mpMsgReply.getMatchMsgTypeDictId()).getCode().equalsIgnoreCase(xml_msg_type_dict_item_prefix +wxMessage.getMsgType()))
                        &&
                        (mpMsgReply.getMatchEventTypeDictId() == null || dictClient.getDictById(mpMsgReply.getMatchEventTypeDictId()).getCode().equalsIgnoreCase(event_type_dict_item_prefix + wxMessage.getEvent()))
                        &&
                        (mpMsgReply.getMatchEventKey() == null || matchType(mpMsgReply.getMatchEventKeyMatchDictId(),mpMsgReply.getMatchEventKey(),wxMessage.getEventKey()))
                        &&
                        (mpMsgReply.getMatchContent() == null || matchType(mpMsgReply.getMatchContentMatchDictId(),mpMsgReply.getMatchContent(),StringUtils.trimToNull(wxMessage.getContent())))

                ;
    }

    /**
     * 根据匹配方式匹配
     * @param matchTypeDictId
     * @param matchRuleValue
     * @param originValue
     * @return
     */
    private boolean matchType(String matchTypeDictId,String matchRuleValue,String originValue){
        Dict dictMatchType = dictClient.getDictById(matchTypeDictId);
        // 相等
        if (PublicDictEnums.DictMatchType.match_eq.name().equals(dictMatchType.getCode())) {
            return matchRuleValue.equalsIgnoreCase(originValue);
        }
        // 模糊
        if (PublicDictEnums.DictMatchType.match_like.name().equals(dictMatchType.getCode())) {
            if (originValue != null) {
                return originValue.contains(matchRuleValue);
            }
        }
        // 左模糊匹配
        if (PublicDictEnums.DictMatchType.match_like_left.name().equals(dictMatchType.getCode())) {
            if (originValue != null) {
                return originValue.startsWith(matchRuleValue);
            }
        }
        // 右模糊匹配
        if (PublicDictEnums.DictMatchType.match_like_right.name().equals(dictMatchType.getCode())) {
            if (originValue != null) {
                return originValue.endsWith(matchRuleValue);
            }
        }
        // 正则匹配
        if (PublicDictEnums.DictMatchType.match_regex.name().equals(dictMatchType.getCode())) {
            return Pattern.matches(matchRuleValue, StringUtils.trimToEmpty(originValue));
        }
        return false;
    }
}
